package csm.web.core;

import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.velocity.context.Context;

import csm.common.StringUtil;
import csm.web.core.sitemap.SiteMap;

public abstract class AjaxServletBase  extends VelocityServletBase{

	/** */
	private static final long serialVersionUID = -1226024209526435693L;
	private HttpSession session = null;
	/**
	 * 세션값을 얻어옵니다.
	 *
	 * @return
	 */
	protected final HttpSession getSession() {
		return session;
	}
	protected void setJsonHeader(HttpServletResponse response, String json) {
		response.addHeader("X-JSON", json);
	}
	public abstract void populate(HttpServletRequest request,
			HttpServletResponse response, Context context) throws Exception;

	@Override
	protected void handleRequest(HttpServletRequest request,
			HttpServletResponse response, Context context) throws Exception {
		String themaName = "thema/default";

		try{
			// ******************************************************************************************************
			// 시스템의 구성적인 요소를 세팅한다. (encoding, locale, cookie speck 등등)
			// ******************************************************************************************************
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setHeader(	"P3P", "CP=\"NOI CURa ADMa DEVa TAIa OUR DELa BUS IND PHY ONL UNI COM NAV INT DEM PRE\"");
			ServletContext ctx = request.getSession().getServletContext();
			session = request.getSession();


			themaName = getThemaName(request);
			context.put("THEMA", themaName);

			// ******************************************************************************************************
			// populate 를 override 하면서, 해당 기능에 필요한 파리메터를 세팅하게 된다.
			// 이러한 세팅은 populate를 구현하는 서블릿에서 직접 처리한다
			// (사실 좀 고민 된다...웹을 잘 아는 기술자가 판정해 주어야 할듯...)
			// ******************************************************************************************************
			populate(request, response, context);


			// ******************************************************************************************************
			// TODO 이곳에서 모든 AJAX 페이지에서 공통으로 사용할 파라메터를 세팅한다.
			// ******************************************************************************************************
			String queryString = request.getQueryString() != null && request.getQueryString().length() > 0 ? "?" + request.getQueryString() : "";
			context.put("CURRENT_URI", request.getRequestURI() + queryString);
			context.put("CURRENT_PATH",getRequestPath(request));
			context.put("ROOT_PATH", request.getContextPath()); // Root path
			context.put("ROOT_FULL_PATH",getRootFullPath(request)); // Root path
			context.put("USER_IP", getClientIp(request));
			if (!csm.common.StringUtil.isNullOrEmpty(request.getQueryString())) // 호출 URL
				context.put("REQUEST_URL",	URLEncoder.encode(String.format("%s?%s", request.getRequestURI(), request.getQueryString()), "UTF-8"));
			else
				context.put("REQUEST_URL", URLEncoder.encode(request.getRequestURI(), "UTF-8"));

			context.put("IS_ADMIN", "N");
		}
		catch(Exception e){
			setJsonHeader(response, "{'result':'false'}");
			context.put("PAGE", themaName + "/errors/error.vm");
			context.put("ErrorMessage", e.getMessage());
			e.printStackTrace(System.err);
		}
		String tempateFile = SiteMap.getInstance().getTemplateFile("BLANK");
		String path= "";
		if( StringUtil.isNullOrEmpty(tempateFile))
			path = "common/blankTemplate.vm";
		else
			path = themaName + "/" + tempateFile;

		forward(context, request, response, path);
	}
}
